package com.zhang.authoritycenter.common.config;

import com.zhang.infrastructure.model.KingHoodResponseVO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Demo class
 * <p>
 * 文件名: WebLog
 * 创建者: zhangfanjun
 * 创建时间:2021/8/18 10:28
 * 描述:
 *
 * @author 000095133
 */
@Aspect
@Component
public class WebLog {
    private final Logger log = LoggerFactory.getLogger(WebLog.class);
    private static final ThreadLocal<Long> START_TIME = new ThreadLocal<>();

    @Pointcut("execution(public * com.zhang.authoritycenter.controller.*.*Controller.*(..))")
    public void infoLog() {
    }

    @Before("infoLog()")
    public void beforeLog(JoinPoint point) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        log.info("请求===>URL:{},参数:{}", request.getRequestURL(), point.getArgs());
        Long start = System.currentTimeMillis();
        START_TIME.set(start);
    }

    @AfterReturning(returning = "result", pointcut = "infoLog()")
    public void doAfterReturning(JoinPoint point, Object result) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        if (result instanceof KingHoodResponseVO){
            Long start = START_TIME.get();
            Long end = System.currentTimeMillis();
            log.info("请求===>URL:{},参数:{},返回值:{},请求耗时;{}毫秒", request.getRequestURL(), point.getArgs(), result,end - start);
            START_TIME.remove();
        }
    }
}
